const serverUploader = require("./serverUploader");
import $H from '@/common/free-lib/request.js';
import $C from '@/common/free-lib/config.js';
export default {
	upload(requestInfo) {
		return new Promise((resolve, reject) => {
			if (Array.isArray(requestInfo.files)) {
				if (requestInfo.url) {
					var url = $C.baseUrl + requestInfo.url
					oss_data.url = url;
					console.log("oss_data.url: " + JSON.stringify(oss_data.url));
					return
				}
				let token = requestInfo.files[0]['token'];
				let len = requestInfo.files.length;
				let fileList = new Array;
				var url = '/mehrb/nffw/oss/upload'
				$H.post(url, 'app', {
					token: true,
					datalist: {
						token: requestInfo.files[0]['token']
					},
				}).then(ret => {
					if (ret.data.status != 200) {
						uni.showModal({
							title: '错误',
							content: ret.data.msg,
							showCancel: false,
							success: function(res) {

							}
						});
					}
					var oss = ret.data.data.oss
					let oss_data = ret.data.data;
					serverUpload(0);

					function serverUpload(i) {
						let item = requestInfo.files[i];
						if (uni.getStorageSync('platform') == 'H5') {
							var domain = window.location.protocol + "//" + window.location.host +
								'/';
							if (domain.indexOf("localhost:") == -1) {
								$C.baseUrl = domain;
							}
						}
						if (oss == 0) {
							var url = $C.baseUrl + 'banmi.php/upload/upload';
							oss_data.url = url;
						}
						item.img_index = i;
						var updateUrl = '';
						let fileData = {
							fileIndex: i,
							files: requestInfo.files,
						};
						oss_data.token = token;
						serverUploader.upload(item, oss_data, (res) => {
							fileData.url = res.imageURL;
							fileList.push(res.imageURL);
							if (len - 1 > i) {
								serverUpload(i + 1);
							} else {
								resolve(fileList);
							}
						}, (error) => {
							reject(error);
						}, (res) => {
							requestInfo.onProgressUpdate && requestInfo.onProgressUpdate(
								Object
								.assign({}, fileData, res));
						});
					}

				});
			} else {
				reject({
					errMsg: "files 必须是数组类型",
					statusCode: 0
				});
			};
		});
	}
}